package com.car.web.controller.interfaceController;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.emay.sdk.client.api.Client;

import com.car.dal.dao.goods.*;
import com.car.dal.dao.grade.TgUsergradeDao;
import com.car.dal.object.*;
import com.car.util.*;

import org.apache.log4j.Logger;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.car.dal.dao.ask.AskDao;
import com.car.dal.dao.client.TgClientDao;
import com.car.dal.dao.method.TgMethodDao;
import com.car.dal.dao.moneys.TgMoneyDao;
import com.car.dal.dao.office.TgOfficeDao;
import com.car.dal.dao.period.TgPeriodDao;
import com.car.dal.dao.pos.TgPosDao;
import com.car.dal.dao.reception.TgReceptionDao;
import com.car.dal.dao.reserve.TgReserveDao;
import com.car.dal.dao.sudent.StudentDao;
import com.car.dal.dao.teastu.TeacherStuDao;
import com.car.dal.dao.tracking.TgTrackingDao;
import com.car.dal.dao.user.UserDao;
import com.car.dal.dao.user.UserinfoDao;
import com.car.dal.dao.vote.JsVoteDao;
import com.car.service.reception.ReceptionService;
import com.car.service.tgPeriod.TgPeriodService;
import com.car.util.JsonExecutor.JsonBiz;
import com.car.util.WebExecutor.Biz;
import com.car.web.controller.base.BaseController;
import com.car.web.controller.base.BaseVo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

/**
 * 登录控制
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/oa")
public class StudentController extends BaseController {
	private static final Logger logger = Logger.getLogger(StudentController.class);
    @Resource
    private AskDao askDao;
    @Resource
    private JsVoteDao voteDao;
    @Resource
    private JsVoteDao jsVoteDao;
    @Resource
	private TgReserveDao reserveDao;
	@Resource
	private TgClientDao clientDao;
	@Resource
	private StudentDao studentDao;
	@Resource
	private UserinfoDao userinfoDao;
	@Resource
	private TgReceptionDao receptionDao;
	@Resource
	private TgMoneyDao moneyDao;
	@Resource
	private TgPosDao posDao;
	@Resource
	private TgOfficeDao tgOfficeDao;
	@Resource
	private TgGoodsDao goodsDao;
	@Resource
	private TgGoodsAccountDao tgGoodsAccountDao;
	@Resource
	private TgGoodsKeyDao tgGoodKeyDao;
	@Resource
    private TgUsergradeDao usergradeDao;
	@Resource
    private UserDao userDao;
	@Resource
    private ReceptionService receptionService;
	@Resource
	private TgPeriodService tgPeriodService;
	@Resource
	private TgPeriodDao  tgPeriodDao;
	@Resource
	private TeacherStuDao teaStuDao;
	@Resource
    private TgTrackingDao trackingDao;
	@Resource
    private TgMethodDao methodDao;
	
	
	
	//获取老师的学生列表
    @RequestMapping(value = "/getStudentList")
   	public ModelAndView getStudentList(ModelMap modelMap, final BaseVo vo ,
   		final HttpServletRequest request, final HttpServletResponse response)
   			throws Exception {
   		modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
   			public Result process() {
   				Result result = new ResultSupport(true);
   				
   				String tea_id = request.getParameter("tea_id");
   				String nickname = request.getParameter("nickname");
   				
   				TeacherStu teaStu = new TeacherStu();
   				teaStu.setTea_id(Long.valueOf(tea_id));
   				teaStu.setNickname(nickname);
	   			Integer currPage = 1;
	            if (vo.getCurrPage() != null && !"".equals(vo.getCurrPage())) {
	                currPage = vo.getCurrPage();
	            }
	            Integer total = teaStuDao.getStudentCouBytea(teaStu);
	            Page page = PageUtil.createPage(8, currPage, total);
	            List<TeacherStu> list = teaStuDao.getStudentListBytea(teaStu, page);
	            result.setDefaultModel("page", page);
	            result.setDefaultModel("list", list);
                return result;
   			}
   		});
   		return new ModelAndView("", modelMap);
   	}
    
	//获取所有的学生列表
    @RequestMapping(value = "/getStuList")
   	public ModelAndView getStuList(ModelMap modelMap, final BaseVo vo ,
   		final HttpServletRequest request, final HttpServletResponse response)
   			throws Exception {
   		modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
   			public Result process() {
   				Result result = new ResultSupport(true);
   				
   				String zx_tea_name = request.getParameter("zx_tea_name");
   				String nickname = request.getParameter("nickname");
   				
   				TgStudent student = new TgStudent();
   				student.setNickname(nickname);
   				student.setZx_tea_name(zx_tea_name);
	   			Integer currPage = 1;
	            if (vo.getCurrPage() != null && !"".equals(vo.getCurrPage())) {
	                currPage = vo.getCurrPage();
	            }
	            Integer total = studentDao.getAllStudentCouByType(student);
	            Page page = PageUtil.createPage(8, currPage, total);
	            List<TgStudent> list = studentDao.getAllStudentListByType(student, page);
	            result.setDefaultModel("page", page);
	            result.setDefaultModel("list", list);
                return result;
   			}
   		});
   		return new ModelAndView("", modelMap);
   	}
    
    //获取所有的学生列表--已缴费
    @RequestMapping(value = "/getStuList2")
   	public ModelAndView getStuList2(ModelMap modelMap, final BaseVo vo ,
   		final HttpServletRequest request, final HttpServletResponse response)
   			throws Exception {
   		modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
   			public Result process() {
   				Result result = new ResultSupport(true);
   				
   				String zx_tea_name = request.getParameter("zx_tea_name");
   				String nickname = request.getParameter("nickname");
   				
   				TgStudent student = new TgStudent();
   				student.setNickname(nickname);
   				student.setZx_tea_name(zx_tea_name);
	            List<TgStudent> list = studentDao.getAllStudentListByType2(student);
	            result.setDefaultModel("list", list);
                return result;
   			}
   		});
   		return new ModelAndView("", modelMap);
   	}
    
    //获取所有的学生列表--已缴费和未交费，但有名字的
    @RequestMapping(value = "/getStuList3")
   	public ModelAndView getStuList3(ModelMap modelMap, final BaseVo vo ,
   		final HttpServletRequest request, final HttpServletResponse response)
   			throws Exception {
   		modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
   			public Result process() {
   				Result result = new ResultSupport(true);
   				
   				String zx_tea_name = request.getParameter("zx_tea_name");
   				String nickname = request.getParameter("nickname");
   				String center = request.getParameter("center");
   				
   				TgStudent student = new TgStudent();
   				student.setNickname(nickname);
   				student.setZx_tea_name(zx_tea_name);
   				student.setCenter(center);
	            List<TgStudent> list = studentDao.getAllStudentListByType3(student);
	            result.setDefaultModel("list", list);
                return result;
   			}
   		});
   		return new ModelAndView("", modelMap);
   	}
    
    //获取学员学生列表，只显示名字和id，不分页
    @RequestMapping(value = "/getStudentList2")
   	public ModelAndView getStudentList2(ModelMap modelMap, final BaseVo vo ,
   		final HttpServletRequest request, final HttpServletResponse response)
   			throws Exception {
   		modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
   			public Result process() {
   				Result result = new ResultSupport(true);
   				
   				String tea_id = request.getParameter("tea_id");
   				String nickname = request.getParameter("nickname");
   				
   				TeacherStu teaStu = new TeacherStu();
   				teaStu.setTea_id(Long.valueOf(tea_id));
   				teaStu.setNickname(nickname);
	            List<TeacherStu> list = teaStuDao.getStudentListBytea2(teaStu);
	            result.setDefaultModel("list", list);
                return result;
   			}
   		});
   		return new ModelAndView("", modelMap);
   	}
    
    //根据id获取学生
    @RequestMapping(value = "/getStudentById")
   	public ModelAndView getStudentById(ModelMap modelMap, final BaseVo vo ,
   		final HttpServletRequest request, final HttpServletResponse response)
   			throws Exception {
   		modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
   			public Result process() {
   				Result result = new ResultSupport(true);
   				String id = request.getParameter("id");
   				if(id!=null && !"".equals(id)){
   		            TgStudent student = studentDao.getStudentById(Long.valueOf(id));
   		            result.setDefaultModel("student", student);
   				}
                return result;
   			}
   		});
   		return new ModelAndView("", modelMap);
   	}
    
    //分配学生
    @RequestMapping(value = "/addTeaStu")
   	public ModelAndView addTeaStu(ModelMap modelMap, final BaseVo vo ,
   		final HttpServletRequest request, final HttpServletResponse response)
   			throws Exception {
   		modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
   			public Result process() {
   				Result result = new ResultSupport(true);
   				
   				String stu_id = request.getParameter("stu_id");
   				String tea_id = request.getParameter("tea_id");
   				
   				TeacherStu teaStu = new TeacherStu();
   				if(tea_id!=null && !"".equals(tea_id) &&
   						stu_id!=null && !"".equals(stu_id)){
   					teaStu.setTea_id(Long.valueOf(tea_id));
   	   				teaStu.setStu_id(Long.valueOf(stu_id));
   	   				if(teaStuDao.countEqual(teaStu)<1){
   	   					teaStu.setCreate_time(new Date());
   	   					teaStuDao.insert(teaStu);
   	   					result.setDefaultModel("msg", "1");
   	   				}else{
   	   					result.setDefaultModel("msg", "2");
   	   				}
   				}else{
   					result.setDefaultModel("msg", "0");
   				}
                return result;
   			}
   		});
   		return new ModelAndView("", modelMap);
   	}
    
    
    //解除关系
    @RequestMapping(value = "/deletefenpei")
   	public ModelAndView deletefenpei(ModelMap modelMap, final BaseVo vo ,
   		final HttpServletRequest request, final HttpServletResponse response)
   			throws Exception {
   		modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
   			public Result process() {
   				Result result = new ResultSupport(true);
   				
   				String id = request.getParameter("id");
   				if(id!=null && !"".equals(id)){
   					teaStuDao.delete(TeacherStu.class, Long.valueOf(id));
   					result.setDefaultModel("msg", "1");
   				}else{
   					result.setDefaultModel("msg", "0");
   				}
                return result;
   			}
   		});
   		return new ModelAndView("", modelMap);
   	}
    

    
  //咨询师业务管理--客户接待数据管理
    @RequestMapping(value = "/receptionlist")
    public ModelAndView receptionlist(ModelMap modelMap, final BaseVo vo,
      	final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
    	modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String knickname = request.getParameter("knickname");
                String snickname = request.getParameter("snickname");
                String phone = request.getParameter("phone");
                String center = request.getParameter("center");
                String stnickname = request.getParameter("stnickname");
                String time = request.getParameter("time");

                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

                TgReception reception = new TgReception();
                if (center != null && !"null".equals(center) && !"".equals(center)) {
                	if(center.equals("成都桐梓林中心")) {
                		reception.setRegionns("成都桐梓(zǐ)林中心");
                		reception.setRegion("成都桐梓(zǐ)林中心");
                	}else if(center.equals("广州区庄中心")) {
                		reception.setRegionns("广州区(ōu)庄中心");
                		reception.setRegion("广州区(ōu)庄中心");
                	}
                }
                if (knickname != null && !"null".equals(knickname) && !"".equals(knickname)) {
                	reception.setKnickname(knickname);
                }
                if (snickname != null && !"null".equals(snickname) && !"".equals(snickname)) {
                    reception.setSnickname(snickname);
                }
                if (stnickname != null && !"null".equals(stnickname) && !"".equals(stnickname)) {
                    reception.setStnickname(stnickname);
                }
                if (phone != null && !"null".equals(phone)&& !"".equals(phone)) {
                    reception.setPhone(phone);
                }
                if (time != null && !"null".equals(time)&& !"".equals(time)) {
                    reception.setTime(time);
                }
                Integer currPage = 1;
                if (vo.getCurrPage() != null && !"".equals(vo.getCurrPage())) {
                    currPage = vo.getCurrPage();
                }
                Integer total = receptionDao.getReceptionCount(reception);
                Page page = PageUtil.createPage(8, currPage, total);
                List<TgReception> list = receptionDao.getReceptionByType(reception, page);
                Gson gson = new Gson();
                if (list != null && list.size() > 0) {
                    TgTracking tracking = new TgTracking();
                    for (TgReception rece : list) {
                        //跟踪条数
                        tracking.setClient(rece.getClient());
                        List<TgTracking> listsize = trackingDao.findByExample(tracking);
                        rece.setTracksize(listsize.size() + "");

                        //日期转换
                        /*if (rece.getDate() != null && !"".equals(rece.getDate())) {
                            String gtime = sdf.format(new Date(rece.getDate() * 1000));
                            rece.setGtime(gtime);
                        }*/
                        //日期转换2
                        if (rece.getMdate() != null && !"".equals(rece.getMdate())) {
                        	String gtime2 = sdf2.format(new Date(rece.getMdate() * 1000));
                        	rece.setGtime(gtime2);
                        }
                        //联系方式
                        if (rece.getPhone() != null && !"".equals(rece.getPhone())) {
                            if (rece.getPhone().contains("[{")) {
                                List<Phone> phone1 = gson.fromJson(rece.getPhone(),
                                        new TypeToken<List<Phone>>() {
                                        }.getType());
                                rece.setPhlist(phone1);
                            }
                        }

                        //学生信息
                        TgClient client = new TgClient();
                        client.setKeyname(rece.getClient());
                        List<TgStudent> stuList = null;

                        List<TgClient> cliList = clientDao.findByExample(client);
                        if (cliList != null && cliList.size() > 0) {
                            TgStudent stu1 = new TgStudent();
                            stu1.setPkey(cliList.get(0).getKeyname());
                            stuList = studentDao.findByExample(stu1);

                            String student = rece.getStudent();
                            if (student != null && !"".equals(student)) {
                                try {
                                    JsonValidator json = new JsonValidator();
                                    Boolean flag = json.validate(student);
                                    String ObjContent = "";
                                    if (flag) {
                                        ObjContent = student;
                                    } else {
                                        byte[] bytes = StringUtil.hexDecode(student);
                                        ObjContent = new String(bytes, "UTF-8");
                                    }
                                    if (ObjContent.contains("key")) {
                                        JSONObject obj = new JSONObject(ObjContent);
                                        List<StuMsg> smlist = new ArrayList<StuMsg>();
                                        if (stuList != null && stuList.size() > 0) {
                                            for (TgStudent s : stuList) {
                                                JSONObject obj2 = null;
                                                if (ObjContent.contains("\"key\":\"" + s.getKeyname() + "\"")) {
                                                    obj2 = obj.getJSONObject(s.getKeyname());
                                                }
                                                if (obj2 != null) {
                                                    StuMsg stuMsg = new StuMsg();
                                                    stuMsg.setKeyname(obj2.getString("key"));
                                                    stuMsg.setMoneylog(obj2.getString("moneylog"));
                                                    stuMsg.setPrice(obj2.getString("price"));
                                                    stuMsg.setReason(obj2.getString("reason"));
                                                    stuMsg.setResult(obj2.getString("result"));
                                                    stuMsg.setTestuser(s.getNickname());
                                                    smlist.add(stuMsg);
                                                }
                                                rece.setSmlist(smlist);
                                            }
                                        }
                                    }
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                    }
                }

                result.setDefaultModel("reception", reception);
                result.setDefaultModel("list", list);
                result.setDefaultModel("page", page);

                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }
    
    
    //咨询师业务管理--接待详情
    @RequestMapping(value = "/jiedaiDetil")
    public ModelAndView jiedaiDetil(ModelMap modelMap, final BaseVo vo,
         final HttpServletRequest request, final HttpServletResponse response)
            throws Exception {
    	modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
            public Result process() {
                Result result = new ResultSupport(true);
                String keyname = request.getParameter("keyname");
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                TgReception res = new TgReception();
                res.setKeyname(keyname);
                List<TgStudent> stuList = null;
                List<TgReception> reslist = receptionDao.getReceptionByKeyname(res);
                Gson gson = new Gson();
                if (reslist != null && reslist.size() > 0) {
                    res = reslist.get(0);
                    TgOffice office = new TgOffice();
                    office.setKeyname(res.getRegion());
                    List<TgOffice> list = tgOfficeDao.findByExample(office);
                    if (list != null && list.size() > 0) {
                        office = list.get(0);
                        TgMethod method = new TgMethod();
                        method.setCenter_id(office.getId());
                        List<TgMethod> mList = methodDao.findByExample(method);
                        result.setDefaultModel("mList", mList);
                    }
                    for (TgReception stu : reslist) {
                        if (stu.getFeature() != null && !"".equals(stu.getFeature())) {
                            boolean flag = StringUtil.getHanzi(stu.getFeature());
                            if (!flag) {
                                try {
                                    byte[] bytes = StringUtil.hexDecode(stu.getFeature());
                                    String ObjContent = new String(bytes, "UTF-8");
                                    stu.setFeature(ObjContent);
                                } catch (Exception e) {
                                    e.printStackTrace();
                                }
                            }
                        }
                        if (stu.getPhone() != null && !"".equals(stu.getPhone())) {
                            if (stu.getPhone().contains("[{")) {
                                List<Phone> phone = gson.fromJson(stu.getPhone(),
                                        new TypeToken<List<Phone>>() {
                                        }.getType());
                                stu.setPhlist(phone);
                            }
                        }
                        if (stu.getDate() != null && !"".equals(stu.getDate())) {
                            String gtime = sdf.format(new Date(stu.getDate() * 1000));
                            stu.setGtime(gtime);
                        }
                        if (stu.getRep_date() != null && !"".equals(stu.getRep_date())) {
                            String req_time = sdf.format(new Date(stu.getRep_date() * 1000));
                            stu.setRep_time(req_time);
                        }
                        if (stu.getRep_date1() != null && !"".equals(stu.getRep_date1())) {
                            String req_time1 = sdf.format(new Date(stu.getRep_date1() * 1000));
                            stu.setRep_time1(req_time1);
                        }
                        if (stu.getEarnest_date() != null && !"".equals(stu.getEarnest_date())) {
                            String ear_time = sdf.format(stu.getEarnest_date() * 1000);
                            stu.setEar_time(ear_time);
                        }
                    }
                }


                result.setDefaultModel("res", res);
                result.setDefaultModel("key", keyname);
                return result;
            }
        });
        return new ModelAndView("", modelMap);
    }
    
    
    @RequestMapping(value = "/addsh")
   	public ModelAndView addsh(ModelMap modelMap, final BaseVo vo,
   			final HttpServletRequest request, final HttpServletResponse response)
   			throws Exception {
    	modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
   			public Result process() {
   				Result result = new ResultSupport(true);
   				
   				String key = request.getParameter("key");
				String state = request.getParameter("state");
				String state_name = request.getParameter("state_name");
				TgReception res = new TgReception();
				
   				if(key!=null && !"".equals(key)){
   					res.setKeyname(key);
   					List<TgReception> list = receptionDao.findByExample(res);
   					if(list!=null){
   						res = list.get(0);
   					}
   					res.setState(Integer.parseInt(state));
   					res.setState_name(state_name);
   					receptionDao.update(res);
   					result.setDefaultModel("msg", "1");
   				}else{
   					result.setDefaultModel("msg", "0");
   				}
   				return result;
   			}
   		});
   		return new ModelAndView("", modelMap);
   	}
    
    
    @RequestMapping(value = "/getStudentByName")
   	public ModelAndView getStudentByName(ModelMap modelMap, final BaseVo vo,
            final HttpServletRequest request, final HttpServletResponse response)
                    throws Exception {
        	modelMap = JsonExecutor.execute(logger, vo, new JsonBiz() {
                public Result process() {
   				Result result = new ResultSupport(true);
   				
				String stunanme = request.getParameter("stu_name");
				
				TgClient cl = new TgClient();
				if(stunanme !=null && !"".equals("stunanme")){
					cl.setStudent(stunanme);
				}
				List<TgClient> tgclist = clientDao.getStudentByName(cl);
				if(tgclist !=null && tgclist.size()>0){
					cl = tgclist.get(0);
					result.setDefaultModel("cl", cl);//训练系统查询学员来源
				}
				
   				return result;
   			}
   		});
   		return new ModelAndView("", modelMap);
   	}
    /**
     * @Title: 方法名：getStu_xufei_xinzeng
     * @Description: 功能描述：获取学员续费或新增记录
     * @author hqD ☺ ^o^
     * @date 2018年1月17日 上午10:05:16
     * @param @return    
     * @return ModelAndView    返回类型
     * @throws ParseException 
     */
    @RequestMapping(value = "/getStu_xufei_xinzeng")
	public ModelAndView getStu_xufei_xinzeng(HttpServletRequest request,long stu_id,String time) throws ParseException {
		ModelAndView mav=new ModelAndView("");
		String startTime = "";
		String endTime = "";
		if(MathUtil.isNotEmpty(time)) {
			startTime = time + "-01";
			endTime = DateUtil.nextMonthFirstDate_two(startTime);
		}
		List<String> money_xufei = moneyDao.getStu_xufei_xinzeng(stu_id, startTime, endTime,1);
		List<String> money_xinzeng = moneyDao.getStu_xufei_xinzeng(stu_id, startTime, endTime,2);
		money_xufei.addAll(money_xinzeng);
		mav.addObject("money",money_xufei);
		return mav;
	}
    
}
